package ma.projet.service;


import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import ma.projet.beans.Medecin;



import ma.projet.interfaces.IDao;
import ma.projet.HibernateUtil;

public class MedecinService implements IDao<Medecin>{

	@Override
	public void create(Medecin o) throws HibernateException {
		Session session = null;
		Transaction tx = null;

		try {
			session = HibernateUtil.getSessionFactory().openSession();
			tx = session.beginTransaction();
			session.save(o);
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Medecin> load() {
		// TODO Auto-generated method stub
		Session session=null;
		List<Medecin> liste;
	try{	
		
		
		session=HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		liste=session.createQuery("From Medecin").list();
		session.getTransaction().commit();
	
		return liste;}
	catch(HibernateException ex)
	{
		session.getTransaction().rollback();
		System.out.println("Liste Vide");
		return null;
	}
	}

	@Override
	public void delete(Medecin o) {
		// TODO Auto-generated method stub
		Session session = null;
		Transaction tx = null;

		try {
			session = HibernateUtil.getSessionFactory().openSession();
			tx = session.beginTransaction();
			session.delete(o);

			tx.commit();
			
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		
	}

	@Override
	public void update(Medecin o) {
		// TODO Auto-generated method stub
		Session session = null;
		Transaction tx = null;

		try {
			session = HibernateUtil.getSessionFactory().openSession();
			tx = session.beginTransaction();
			session.update(o);
			tx.commit();
			
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			
			session.close();
		}
	
	}

	@Override
	public Medecin getById(int id) {
		// TODO Auto-generated method stub
		Session session = HibernateUtil.getSessionFactory().openSession();
        session.getTransaction().begin();
        Medecin p = (Medecin) session.get(Medecin.class,id);
        session.getTransaction().commit();
        session.close();
        return p;
	}

	
}
